//
//  QandAViewController.m
//  eBook
//
//  Created by zhy on 12-12-20.
//  Copyright (c) 2012年 zhan. All rights reserved.
//

#import "QandAViewController.h"

#define QandAAPI @"http://jpkc.gdou.com/api/Api/QA/?question="

@interface QandAViewController ()

@end

@implementation QandAViewController
@synthesize sendBtn;
@synthesize chatTableView;
@synthesize sendTextField;
@synthesize enterView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    chatTableView.delegate = self;
    chatTableView.dataSource =self;
    chatTableView.backgroundColor = [UIColor clearColor];
    //去横线
    chatTableView.separatorStyle = NO;
    testArray = [NSMutableArray arrayWithObjects:nil];
    
    
    //shoadow
//    self.view.layer.shadowPath =[UIBezierPath bezierPathWithRect:self.view.bounds].CGPath;
//    self.view.layer.shadowColor = [UIColor clearColor].CGColor;
//    self.view.layer.shadowOpacity = 0.4f;
//    self.view.layer.shadowOffset = CGSizeMake(-12.0, 1.0f);
//    self.view.layer.shadowRadius = 7.0f;
//    self.view.layer.masksToBounds = NO;
    
    
    enterView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"dy_bg.png"]];
    
}

- (void)viewDidUnload
{
    [self setChatTableView:nil];
    [self setSendTextField:nil];
    [self setEnterView:nil];
    [self setSendBtn:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

#pragma mark - Private Method
-(NSString *) loadAnswer:(NSString *) keyword{
    
    NSString *urlstr = [NSString stringWithFormat:@"%@%@",QandAAPI,keyword];
    urlstr = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"url is %@",urlstr);
    
    NSString *answer;
    
    NSURL *url = [NSURL URLWithString:urlstr];
    NSData *jsonData = [NSData dataWithContentsOfURL:url];
    
    if (jsonData) {
        
        NSError *error;
        NSMutableArray *result = [[NSMutableArray alloc] init];
        result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        NSLog(@"error:%@",error);
        
        NSLog(@"result count is %d",[result count]);
        
        if ([result count] == 0) {
            answer = @"对不起，系统无法搜索到相关信息。";
        } else {
            answer = [NSString stringWithFormat:@"%@  \n  %@",[[result objectAtIndex:0] valueForKey:@"Title" ],[[result objectAtIndex:0] valueForKey:@"Memo" ]];
        }

    } else{
        answer = @"对不起，系统无法搜索到相关信息。";
    }
    
    return answer;
}


#pragma mark - Action
- (IBAction)sendAction:(id)sender {
    NSString *str = [sendTextField text];
    
    if ([str isEqualToString:@""]) {
        NSLog(@"nil");
    } else{
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"me",@"who",str,@"content",nil];
        
        [testArray addObject:dic];
        
        if ([str isEqualToString:@"你好"]) {
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"answer",@"who",@"你好！",@"content",nil];
            [testArray addObject:dic];
        } else {
            
            dispatch_queue_t   downloadQueue = dispatch_queue_create("data downloader", NULL);
            dispatch_async(downloadQueue, ^{
                NSString *result =  [self loadAnswer:str];
                //UIKit只能在main_queue中
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"answer",@"who",result,@"content" ,nil];
                    [testArray addObject:dic];
                    [chatTableView reloadData];
                });
            });
            dispatch_release(downloadQueue);
            
    
        }
        
//        if ([str isEqualToString:@"你好"]) {
//            [testArray addObject:@"你好！"];
//        } else if ([str isEqualToString:@"教育技术"]){
//            [testArray addObject:@"教育技术是关于学习过程与学习资源的设计、开发、利用、管理和评价的理论与实践。"];
//        } else {
//            [testArray addObject:@"对不起，系统无法搜索到相关信息。"];
//        }
        
        
    }
    
    [chatTableView reloadData];
    [sendTextField setText:@""];
    [sendTextField resignFirstResponder];
    
}

#pragma mark - tableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [testArray count];
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat contentWidth = 170;
    UIFont *font = [UIFont systemFontOfSize:14];
    NSString *content = [[testArray objectAtIndex:indexPath.row] valueForKey:@"content"];
    CGSize size = [content sizeWithFont:font constrainedToSize:CGSizeMake(contentWidth, 1000) lineBreakMode:UILineBreakModeWordWrap];
    
    return size.height+60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"ChatTableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    CGFloat contentWidth = 170;
    UIFont *font = [UIFont systemFontOfSize:14];
    NSString *content = [[testArray objectAtIndex:indexPath.row] valueForKey:@"content"];
    CGSize size = [content sizeWithFont:font constrainedToSize:CGSizeMake(contentWidth, 1000) lineBreakMode:UILineBreakModeWordWrap];
    
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.subviews];
    for (UIView *subview in subviews) {
        [subview removeFromSuperview];
    }
    
    UIImageView *imgview = [[UIImageView alloc] init];
    UITextView *textView = [[UITextView alloc] init];
    if ([[[testArray objectAtIndex:indexPath.row] valueForKey:@"who"] isEqual:@"me"]) {//right
        imgview.frame = CGRectMake(300-size.width-30-14, 10, size.width+30, size.height+20);
        imgview.image = [[UIImage imageNamed:@"dy_talk1.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(20,5,5,15)];
        
        textView.frame = CGRectMake(5, 0, imgview.frame.size.width-5, imgview.frame.size.height-5);
        
//        NSLog(@"size %@",NSStringFromCGSize(size));
//        NSLog(@"frame %@",NSStringFromCGRect(imgview.frame));
//        NSLog(@"text %@",NSStringFromCGRect(textView.frame));
        
    } else{//left
        imgview.frame = CGRectMake(14, 10, size.width+30, size.height+20);
        imgview.image = [[UIImage imageNamed:@"dy_talk.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(20,15,5,5)];
        
        textView.frame = CGRectMake(5, 0, imgview.frame.size.width-5, imgview.frame.size.height-5);
//        textView.frame = CGRectMake(10, 0, size.width+30, size.height+30);
    }
    
    textView.backgroundColor = [UIColor clearColor];
    textView.text = content;
    textView.font = [UIFont systemFontOfSize:14];
    textView.textColor = [UIColor colorWithRed:23.0/255 green:126.0/255 blue:194.0/255 alpha:1.0];
    [imgview addSubview:textView];
    [cell addSubview:imgview];
    
    cell.userInteractionEnabled = NO;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"row is %d",indexPath.row);
    
}

@end
